<template>
  <div class="puls">
    <section class="header">
      <div class="vip">
        <div class="avatar">
          <img
            :src="userInfo.blogProfilePhoto"
            alt=""
            v-if="!!userInfo.blogProfilePhoto"
          />
          <img src="~static/my/user.png" alt="" v-else />
        </div>
        <div class="right">
          <div class="phone">
            {{
              this.phone &&
                this.phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")
            }}
            <img
              class="cardImg"
              v-if="
               userInfo.superInfo &&  userInfo.superInfo.status !=0 && userInfo.superInfo.superName == '月卡'
              "
              src="~static/plus/month.png"
              alt=""
            />
            <img
              class="cardImg"
              v-if="
                userInfo.superInfo && userInfo.superInfo.status !=0 && userInfo.superInfo.superName == '季卡'
              "
              src="~static/plus/season.png"
              alt=""
            />
            <img
              class="cardImg"
              v-if="
                userInfo.superInfo && userInfo.superInfo.status !=0 && userInfo.superInfo.superName == '年卡'
              "
              src="~static/plus/year.png"
              alt=""
            />
          </div>
          <div class="tip">
            <!--<span class="icon issvip"></span>-->
            {{
             (userInfo.superInfo && userInfo.superInfo.status !=0)
                ? userInfo.superInfo.endTime + "到期"
                : "尚未开通SVIP超级会员"
            }}
          </div>
        </div>
      </div>
    </section>
    <section class="content">
      <section class="select">
        <div class="title">请选择开通时长</div>
        <div class="box_1">
          <div class="options">
            <div
              class="option"
              :class="[selectedSuper.superId == ele.superId ? 'selected' : '']"
              v-for="ele in superList"
              :key="ele.superId"
              @click="hanldSelectedSuper(ele)"
            >
              <div class="name">
                {{ ele.showName }}
                <!-- {{ ele.superName === "年卡" ? "礼品卡" : ele.superName }} -->
              </div>
              <div class="amt">
                <span>￥</span>{{ (+ele.price).toFixed(2) }}
              </div>
              <div class="origin">￥{{ (+ele.originalPrice).toFixed(2) }}</div>
            </div>
          </div>
        </div>
      </section>
      <section class="power">
        <div class="title">会员尊贵权益</div>
        <div class="box_1">
          <div class="rights"></div>
        </div>
      </section>
      <section class="detail">
        <div class="title">会员权益详情</div>
        <div class="box_1">
          <ul>
            <li v-for="v in textList" :key="v" class="circle">{{ v }}</li>
          </ul>
          <ul v-if="isEmptyObject">
            <li class="circle">详情请咨询加油站工作人员</li>
          </ul>
        </div>
      </section>
      <section class="pay">
        <van-button
          class="btn"
          :class="[]"
          :loading="!!(payLoading || stationLoading)"
          loading-text="支付中..."
          @click="pay"
          :disabled="
            payLoading || !selectedSuper.superId || !selectedStation.stationId
          "
        >
          <span class="amount"
            ><span class="yuan">￥</span
            >{{
              (+(!!this.selectedSuper.price
                ? this.selectedSuper.price
                : 0)).toFixed(2)
            }}</span
          >
          <span class="text"
            >立刻{{ !!userInfo.superInfo ? "续费" : "开通" }}</span
          >
        </van-button>
        <div class="tip">
          开通即代表同意
          <router-link
            :to="'/' + enterpriseId + '/plus/text'"
            style="color: #9194AC;"
            >《超级会员服务协议》</router-link
          >
        </div>
      </section>
    </section>

    <!-- 选择油站面板 -->
    <van-action-sheet
      v-model="stationShow"
      :actions="stationActions"
      @select="onStationSelect"
      close-on-click-action
      cancel-text="取消"
    />
  </div>
</template>

<script>
import ProductList from "@/components/ProductList";
import { mapState, mapGetters, mapActions } from "vuex";
import wx from "weixin-js-sdk";
import Vue from "vue";
import { Toast, Button, Popup, NumberKeyboard } from "vant";
import { ActionSheet } from "vant";

Vue.use(Popup);
Vue.use(Toast);
Vue.use(Button);
Vue.use(NumberKeyboard);
Vue.use(ActionSheet);

export default {
  head() {
    return {
      title: "SVIP超级会员开通"
    };
  },
  data() {
    return {
      superList: [],
      selectedSuper: {},
      payLoading: false,
      stationLoading: true,
      stationAction: [],
      stationShow: false,
      selectedStation: {},
      stationActions: [],
      textList: []
    };
  },
  components: {
    ProductList
  },
  watch: {
    selectedSuper: {
      handler(newVal) {
        this.textList =
          newVal.superUserTerm && newVal.superUserTerm.split("\n");
      }
    }
  },

  computed: {
    ...mapState({
      pointInfo: state => state.point.pointInfo
    }),
    ...mapGetters({
      userInfo: "authen/userInfo"
    }),
    isEmptyObject() {
      // 判断对象是否为空
      return (
        Object.keys(this.selectedSuper).length === 0 &&
        this.selectedSuper.constructor === Object
      );
    }
    // detailRule1() {
    //   if (this.superList.length == 0) {
    //     return "1.超级会员分为月卡、季卡、 年卡；";
    //   }
    //   let text = "1.超级会员分为";
    //   this.superList.map(ele => {
    //     text += ele.superName + "、";
    //   });
    //   text.replace(/、$/, "；");
    //   return text;
    // },
    // detailRule2() {
    //   if (this.superList.length == 0) {
    //     return " 2.月卡有效期为1个自然月，季卡有效期为3个自然月，年卡有效期为12个自然月；";
    //   }
    //   let text = "2.";
    //   this.superList.map(ele => {
    //     text += ele.superName + "的有效期为" + ele.cycle + "个自然天，";
    //   });
    //   text.replace(/，$/, "；");
    //   return text;
    // }
  },
  created() {
    this.tempEnterpriseId =
      this.$route.query.enterpriseId || sessionStorage.getItem("enterpriseId");

    sessionStorage.setItem("enterpriseId", this.tempEnterpriseId);
    $nuxt.$store.commit("authen/setEnterpriseId", this.tempEnterpriseId);
    // 版本3
    // if (!this.tempEnterpriseId) {
    //   alert("此页面不支持直接访问");
    //   return;
    // }
    // this.init();

    // 版本1
    // if(!!this.phone){
    //   this.init();
    // }

    // 版本2
    setTimeout(() => {
      const phone = this.phone;
      // const appId = $nuxt.$store.getters["authen/appId"];
      if (!this.tempEnterpriseId) {
        alert("此页面不支持直接访问");
        return;
      }
      this.init();
    }, 500);
  },
  methods: {
    ...mapActions({
      getSdkConfig: "authen/getSdkConfig"
    }),

    // 选择面板的油站
    onStationSelect(q) {
      this.selectedStation = q;
    },

    // 选择某个卡
    hanldSelectedSuper(row) {
      this.selectedSuper = row;
    },

    init() {
      // 获取油站列表
      this.$axios
        .$get("/selectStaInfoList", {
          params: {
            enterpriseId: this.tempEnterpriseId
          }
        })
        .then(res => {
          if (res.retCode === 0) {
            if (!!res.data) {
              this.stationActions = res.data.map(ele => {
                return { ...ele, name: ele.stationName };
              });

              if (this.stationActions.length == 1) {
                this.selectedStation = this.stationActions[0];
                this.stationShow = false;
              } else {
                this.stationShow = true;
              }
              this.stationLoading = false;
            }
          }
        });

      // 获取年卡，季卡，月卡，礼品卡等信息
      this.$axios
        .$post("/appUserSuperList", {
          enterpriseId: this.enterpriseId
        })
        .then(res => {
          if (res.retCode != 0) {
            throw new Error(res.message);
          }
          this.superList = res.data;
          this.hanldSelectedSuper(this.superList && this.superList[0]);
        })
        .catch(err => {
          alert(err);
        });
    },

    // 立即开通 、  立即续费
    async pay() {
      this.payLoading = true;
      try {
        const orderData = await this.$axios.$post("/createSuperPayOrder", {
          superId: this.selectedSuper.superId,
          mobilePhone: this.phone,
          stationId: this.selectedStation.stationId
        });

        if (orderData.retCode !== 0) {
          throw new Error(orderData.message);
        }

        console.log(orderData);

        const orderNum = orderData.data;
        const payInfoData = await this.$axios.$post(
          "/appUserSuperToThirdPayment",
          {
            openId: this.openId,
            enterpriseId: this.enterpriseId,
            orderNo: orderNum,
            userType: "1"
          }
        );
        console.log("payInfoData", payInfoData);

        if (payInfoData.retCode !== 0) {
          throw new Error(payInfoData.message);
        }

        const timestamp = payInfoData.data.payTimeStamp;
        const nonceStr = payInfoData.data.paynonceStr;
        const packageOrg = payInfoData.data.payPackage;
        const signType = payInfoData.data.paySignType;
        const paySign = payInfoData.data.paySign;

        const that = this;
        if (payInfoData.data.thirdPayment === "5") {
          console.log("云化支付");
          window.location.href = payInfoData.data.redirectUrl;
        } else {
          console.log("随行付");
          WeixinJSBridge.invoke(
            "getBrandWCPayRequest",
            {
              appId: payInfoData.data.payAppId,
              timeStamp: payInfoData.data.payTimeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: payInfoData.data.paynonceStr, // 支付签名随机串，不长于 32
              package: payInfoData.data.payPackage, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: payInfoData.data.paySignType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: payInfoData.data.paySign // 支付签名
            },
            function(res) {
              if (res.err_msg === "get_brand_wcpay_request:ok") {
                // 使用以上方式判断前端返回,微信团队郑重提示：
                //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                that.payLoading = false;
                Toast("支付成功");
              } else {
                that.payLoading = false;
                Toast("支付失败，请重试");
              }
            }
          );
        }

        // 拉取微信支付
        // this.getSdkConfig({
        //   jsApiList: ["chooseWXPay"],
        // }).then((res) => {
        //   wx.config(res);
        //   wx.ready(function (res) {
        //     wx.chooseWXPay({
        //       timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        //       nonceStr, // 支付签名随机串，不长于 32 位
        //       package: packageOrg, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
        //       signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        //       paySign, // 支付签名
        //       success: function (res) {
        //         that.payLoading = false;
        //         alert("支付完成");
        //       },
        //       cancel: function (err) {
        //         that.payLoading = false;
        //         alert("您取消了付款");
        //       },
        //       fail: function (err) {
        //         that.payLoading = false;
        //         alert(err);
        //       },
        //     });
        //   });
        //   wx.error(function (res) {
        //     alert("拉取微信Sdk配置出错");
        //   });
        // });
      } catch (err) {
        this.payLoading = false;
        alert(err);
      } finally {
        this.payLoading = false;
      }
    }
  }
};
</script>

<style lang="scss">
.puls {
  position: relative;
  .box_1 {
    background-color: #feffff;
    border-radius: 0.2rem;
    padding: 0.2rem;
    box-sizing: border-box;
    ul {
      margin-left: 0.2rem;
      li {
        text-indent: -1em;
      }
    }
    ul li:before {
      content: "";
      border: 1px solid #fd6b00; /* 设置外层圆圈边框样式和颜色 */
      display: inline-block;
      width: 4px; /* 设置固定的宽度 */
      height: 4px; /* 设置固定的高度 */
      border-radius: 50%; /* 将外层圆圈设为圆形 */
      position: relative; /* 设置相对定位 */
      margin-right: 0.5em; /* 留出一定的间距 */
      vertical-align: middle; /* 垂直居中 */
    }
    .circle {
      color: #333333;
      margin-right: 0.1rem;
      margin-top: 0.1rem;
    }
  }
  .header {
    overflow: hidden;
    background: url("~static/plus/cover.png") no-repeat 0px 0px;
    background-size: 100% 100%;
    height: 20vh;
    .vip {
      display: flex;
      justify-content: center;
      align-items: flex-start;
      background: url("~static/plus/card.png") no-repeat;
      // background-size: contain;
      background-size: 100% 16vh;
      width: 6.88rem;
      margin: 0 auto;
      height: 16vh;
      margin-top: 0.4rem;
      // height: 100%;
      padding: 0.3rem 0 0 0.3rem;
      box-sizing: border-box;
      border-radius: 0.1rem 0.1rem 0 0;
    }
    .avatar {
      width: 1rem;
      height: 1rem;
      border-radius: 0.65rem;
      overflow: hidden;
      > img {
        width: 100%;
        height: 100%;
      }
    }
    .right {
      width: 5.5rem;
      height: 1rem;
      color: white;
      margin-left: 0.3rem;
      .phone {
        line-height: 0.6rem;
        height: 0.6rem;
        font-size: 0.3rem;
        color: #0e037b;
        .cardImg {
          margin-left: 0.2rem;
          padding-top: 0.15rem;
          width: 0.75rem;
          height: 0.3rem;
        }
      }
      .tip {
        color: #ffffff;
        opacity: 0.8;
        line-height: 0.4rem;
        height: 0.4rem;
        font-size: 0.25rem;
        .icon {
          display: inline-block;
          width: 0.6rem;
          height: 0.4rem;
          vertical-align: middle;
          background: url("~static/bj.png") no-repeat 0px 0px;
          background-size: 100% 100%;
        }
        .issvip {
          background: url("~static/personal/bj2@2x.png") no-repeat 0px 0px;
          background-size: 100% 100%;
        }
      }
    }
  }
  .content {
    width: 100%;
    box-sizing: border-box;
    border-radius: 0.3rem 0.3rem 0 0;
    background-color: #f6f7f9;
    overflow: hidden;
    overflow-y: auto;
    position: absolute;
    margin-top: -2vh;
    // margin-top: -0.2rem;
    // padding-bottom: 0.3rem;
    height: calc(100vh - 18vh);

    .select {
      box-sizing: border-box;
      padding: 0.3rem 0.2rem 0rem 0.2rem;
      // background-color: #feffff;
      height: 3.7rem;
      .title {
        font-size: 0.31rem;
        font-weight: bold;
        margin-bottom: 0.25rem;
        border-left: 3px solid #fd6b00;
        padding-left: 0.1rem;
      }
      .box_1 {
        min-height: 16vh;
      }
      .options {
        width: 100%;
        display: flex;
        justify-content: space-between;
        text-align: center;
        overflow-x: auto;
        .option {
          box-sizing: border-box;
          background: url("~static/plus/bj.png") no-repeat 0px 0px;
          background-size: 100% 100%;
          width: 2rem;
          flex-shrink: 0;
          height: 2.2rem;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          padding: 0.1rem;
          margin: 0 0.1rem;
          .name {
            // width: 1.5rem;
            font-size: 0.3rem;
            font-weight: bold;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
          }
          .amt {
            font-size: 0.4rem;
            color: #ff4445;
            > span {
              font-size: 0.25rem;
            }
          }
          .origin {
            line-height: 0.28rem;
            font-size: 0.28rem;
            text-decoration: line-through;
            color: #999a9b;
          }
        }
        .selected {
          background: url("~static/plus/bjActive.png") no-repeat 0px 0px;
          background-size: 100% 100%;
        }
      }
    }
    .power {
      box-sizing: border-box;
      padding: 0.3rem 0.2rem 0rem 0.2rem;
      height: 3rem;
      // margin-top: 0.2rem;
      .box_1 {
        padding: 0;
      }
      .title {
        font-size: 0.31rem;
        font-weight: bold;
        margin-bottom: 0.25rem;
        border-left: 3px solid #fd6b00;
        padding-left: 0.1rem;
      }
      .rights {
        display: flex;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 0.3rem;
        height: 2rem;
        background: url("~static/plus/Rights.png") no-repeat 0 0;
        background-size: 100% 100%;
        .right {
          height: 2rem;
          width: 2rem;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;

          .icon {
            width: 0.8rem;
            height: 0.8rem;
            display: inline-block;
            background: url("~static/common/a01_jifen@2x.png") no-repeat 0px 0px;
            background-size: 100% 100%;
          }
          .text {
            margin-top: 0.2rem;
            font-size: 0.27rem;
            color: #5e605e;
            text-align: center;
          }
        }
        .strategy {
          .icon {
            background: url("~static/plus/plus_discount.png") no-repeat 0px 0px;
            background-size: 100% 100%;
          }
        }
        .conpon {
          .icon {
            background: url("~static/plus/plus_coupon.png") no-repeat 0px 0px;
            background-size: 100% 100%;
          }
        }
        .point {
          .icon {
            background: url("~static/plus/plus_point.png") no-repeat 0px 0px;
            background-size: 100% 100%;
          }
        }
      }
    }
    .detail {
      .box_1 {
        box-sizing: border-box;
        padding-bottom: 0.2rem;
        overflow-y: auto;
        min-height: 16vh;
      }
      box-sizing: border-box;
      padding: 0.3rem 0.2rem 2rem 0.2rem;
      // background-color: #feffff;
      // margin-top: 0.2rem;
      .title {
        font-size: 0.31rem;
        font-weight: bold;
        margin-bottom: 0.25rem;
        border-left: 3px solid #fd6b00;
        padding-left: 0.1rem;
      }
      .rules {
        color: #656667;
        .rule {
          font-size: 0.27rem;
        }
      }
    }
    .pay {
      width: 100%;
      // background-color: #fff;
      margin-top: 0.2rem;
      padding-bottom: 0.1rem;
      position: fixed;
      bottom: 0.1rem;
      .btn {
        width: 6.24rem;
        height: 1rem;
        background: linear-gradient(-67deg, #fdb816, #fb8b0a);
        background: url("~static/plus/button.png") no-repeat 0 0;
        background-size: 100% 100%;
        border-radius: 0.3rem;
        text-align: center;
        line-height: 0.75rem;
        border: none;
        box-sizing: border-box;
        color: white;
        margin-top: 0.2rem;
        margin-left: 0.615rem;

        .van-button__text {
          display: flex;
          justify-content: space-between;
          width: 100%;
          padding: 0 0.2rem;
          align-items: center;
        }
        .amount {
          font-size: 0.4rem;
          color: #f0d4b3;
          .yuan {
            font-size: 0.23rem;
          }
        }

        .text {
          font-size: 0.3rem;
          margin-left: 0.2rem;
          color: #000;
        }
      }
      .tip {
        margin-top: 0.1rem;
        text-align: center;
        color: #9194ac;
        > span {
          color: #dcb884;
        }
      }
    }
  }
}
</style>
